package cn.xd.base.controller.admin;

import cn.hutool.core.util.ObjUtil;
import cn.hutool.crypto.SecureUtil;
import cn.xd.base.application.dto.cmd.CheckAccountDTO;
import cn.xd.base.application.dto.cmd.CheckUserIdDTO;
import cn.xd.base.application.dto.query.AdminUserQuery;
import cn.xd.base.application.service.command.AdminUserAppService;
import cn.xd.base.application.service.query.AdminMenuQueryAppService;
import cn.xd.base.application.service.query.AdminOrgQueryAppService;
import cn.xd.base.application.service.query.AdminUserQueryAppService;
import cn.xd.base.domain.bean.command.AddAdminUserCommand;
import cn.xd.base.domain.bean.command.UpdateAdminUserCommand;
import cn.xd.base.domain.bean.command.common.ChangeStatusCommand;
import cn.xd.base.domain.bean.response.AdminOrgDTO;
import cn.xd.base.domain.bean.response.AdminUserDTO;
import cn.xd.base.domain.bean.response.AdminUserDetailDTO;
import cn.xd.base.domain.bean.response.JsonAdminMenuTree;
import cn.xd.common.constant.AuthConstant;
import cn.xd.common.domain.auth.CurrentUser;
import cn.xd.common.enums.auth.AppUserTypeEnum;
import cn.xd.common.response.ResponseResult;
import cn.xd.web.utils.SecurityUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import jakarta.annotation.Resource;
import jakarta.validation.Valid;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * 用户管理（adminUser）
 *
 * @author mirzalin
 */
@RestController
@RequestMapping("/admin/user")
public class AdminUserController {
    @Resource
    private AdminUserAppService adminUserAppService;
    @Resource
    private AdminUserQueryAppService adminUserQueryAppService;

    @Resource
    private AdminOrgQueryAppService adminOrgQueryAppService;
    @Resource
    private AdminMenuQueryAppService adminMenuQueryAppService;
    @Resource
    private RedisTemplate<String, Object> redisTemplate;

    /**
     * 新增
     *
     * @param command
     * @return
     */
    @PostMapping("/add")
    public ResponseResult<?> add(@Valid @RequestBody AddAdminUserCommand command) {
        adminUserAppService.addAdminUser(command, SecurityUtils.getUserId());
        return ResponseResult.success();
    }

    /**
     * 更新
     *
     * @param command
     * @return
     */
    @PostMapping("/update")
    public ResponseResult<?> update(@Valid @RequestBody UpdateAdminUserCommand command) {
        List<Long> orgIds = adminOrgQueryAppService.getAdminOrgChildrenIds(SecurityUtils.getAdminUserOrgId());
        adminUserAppService.updateAdminUser(command, orgIds, SecurityUtils.getUserId());
        return ResponseResult.success();
    }

    /**
     * 更新状态
     *
     * @param command
     * @return
     */
    @PostMapping("/change/Status")
    public ResponseResult<?> changeAdminRoleStatus(@Valid @RequestBody ChangeStatusCommand command) {
        adminUserAppService.changeAdminUserStatus(command, SecurityUtils.getUserId());
        return ResponseResult.success();
    }

    /**
     * 删除
     *
     * @param id 删除的用户id
     * @return
     */
    @PostMapping("/delete/{id}")
    public ResponseResult<?> delete(@PathVariable Long id) {
        List<Long> orgIds = adminOrgQueryAppService.getAdminOrgChildrenIds(SecurityUtils.getAdminUserOrgId());
        adminUserAppService.delete(id, orgIds);
        return ResponseResult.success();
    }

    /**
     * 查询用户明细
     *
     * @param id
     * @return
     */
    @PostMapping("/info/{id}")
    public ResponseResult<AdminUserDetailDTO> getInfo(@PathVariable Long id) {
        return ResponseResult.success(adminUserQueryAppService.getInfo(id));
    }

    /**
     * 检查账号是否存在
     *
     * @param checkAccountDTO
     * @return
     */
    @PostMapping("/checkHasAccount")
    public ResponseResult<Boolean> checkHasAccount(@Validated @RequestBody CheckAccountDTO checkAccountDTO) {
        return ResponseResult.success(adminUserQueryAppService.checkHasAccount(checkAccountDTO.getAccount(), checkAccountDTO.getId()));
    }

    /**
     * 检查GlobalUser是否被绑定
     *
     * @param checkAccountDTO
     * @return
     */
    @PostMapping("/checkHasGlobalUser")
    public ResponseResult<Boolean> checkHasGlobalUser(@Validated @RequestBody CheckUserIdDTO checkAccountDTO) {
        return ResponseResult.success(adminUserQueryAppService.checkHasGlobalUser(checkAccountDTO.getUserId(), checkAccountDTO.getId()));
    }


    /**
     * 查询当前用户信息（redis）
     *
     * @return
     */
    @PostMapping("/getInfo")
    public ResponseResult<Map<String, Object>> getInfo() {
        CurrentUser user = SecurityUtils.getUser();
        Long adminUserOrgId = SecurityUtils.getAdminUserOrgId();
        adminUserOrgId = adminUserOrgId == null ? 0L : adminUserOrgId;
        String jwtKey = String.format(AuthConstant.AUTH_USER_KEY_FORMAT, user.getAppUserType().getCode(), user.getUserSource().getCode(), user.getId(), adminUserOrgId);
        String key = (String) redisTemplate.opsForValue().get(jwtKey);
        String userInfoKey = String.format(AuthConstant.AUTH_USER_INFO_FORMAT, key);
        String userPermKey = String.format(AuthConstant.AUTH_USER_PERM_FORMAT, key);
        List<String> userPerm = Objects.requireNonNull(redisTemplate.opsForSet().members(userPermKey)).stream().map(Object::toString).toList();
        Object userInfo = redisTemplate.opsForValue().get(userInfoKey);
        List<JsonAdminMenuTree> adminMenuJsonTree = adminMenuQueryAppService.getAdminMenuJsonTree(0L, userPerm);
        Map<String, Object> res = new HashMap<>();
        res.put("info", userInfo);
        res.put("perms", userPerm);
        res.put("menus", adminMenuJsonTree);
        return ResponseResult.success(res);
    }

    /**
     * 查询用户（分页）
     *
     * @param query
     * @return
     */
    @PostMapping("/page")
    public ResponseResult<Page<AdminUserDTO>> getPage(@RequestBody AdminUserQuery query) {
        List<Long> orgIds = adminOrgQueryAppService.getAdminOrgChildrenIds(SecurityUtils.getAdminUserOrgId());
        return ResponseResult.success(adminUserQueryAppService.getPage(query, orgIds));
    }

    /**
     * 查询用户（不分页）
     *
     * @param query
     * @return
     */
    @PostMapping("/list")
    public ResponseResult<List<AdminUserDTO>> getList(@RequestBody AdminUserQuery query) {
        List<Long> orgIds = adminOrgQueryAppService.getAdminOrgChildrenIds(SecurityUtils.getAdminUserOrgId());
        return ResponseResult.success(adminUserQueryAppService.getList(query, orgIds));
    }

    /**
     * 查询用户机构
     *
     * @return
     */
    @PostMapping("/getUserOrgs")
    public ResponseResult<List<AdminOrgDTO>> getUserOrgs() {
        if (SecurityUtils.getUser().getAppUserType().equals(AppUserTypeEnum.MAIN_ADMIN)) {
            return ResponseResult.success(new ArrayList<>());
        }
        Long adminUserIdByGlobalUserId = adminUserQueryAppService.getAdminUserIdByGlobalUserId(SecurityUtils.getCustomerUserId());
        if (ObjUtil.isEmpty(adminUserIdByGlobalUserId)) {
            return ResponseResult.success(new ArrayList<>());
        }
        return ResponseResult.success(adminUserQueryAppService.getOrgsByAdminUserId(adminUserIdByGlobalUserId));
    }
}
